package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : lenovo
 * @date: 2024/12/29 21:52
 */
@Service
public class ApUserServiceImpl implements IApUserService {

    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto loginDto) {
        Map<String,Object> result = new HashMap<>();

        if(StringUtils.isNoneEmpty(loginDto.getPhone()) && StringUtils.isNoneEmpty(loginDto.getPassword())){
            //根据手机号查询用户信息
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser apUser = apUserMapper.selectOne(wrapper);
            if(apUser == null){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //获取salt
            //将输入的密码+salt md5
            String inputPs = loginDto.getPassword() + apUser.getSalt();
            String inputPsMd5 = DigestUtils.md5DigestAsHex(inputPs.getBytes());
            //比较密码是否正确
            if(!inputPsMd5.equals(apUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //构造返回数据
            //去掉敏感数据
            apUser.setPassword("");
            result.put("user",apUser);
            result.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
        }else{
            //游客登录
            //去掉敏感数据
            result.put("token", AppJwtUtil.getToken(0L));
        }
         return ResponseResult.okResult(result);

    }
}
